package com.nowcoder.community.service;

import com.nowcoder.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DataService {

    private final DateFormat df = new SimpleDateFormat("yyyMMdd");

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    // 将指定IP记入UV
    public void recordUV(String ip) {
        String uvKey = RedisKeyUtil.getUVKey(df.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(uvKey, ip);
    }

    // 计算连续多天的UV总数
    public long calculateUV(Date start, Date end) {
        if (start == null || end == null) {
            throw new IllegalArgumentException("参数不能为空！");
        }

        if (start.after(end)) {
            return 0;
        }

        // 获取该时间范围内每天的uvKey
        List<String> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)) {
            keyList.add(RedisKeyUtil.getUVKey(df.format(calendar.getTime())));
            calendar.add(Calendar.DATE, 1);
        }

        return redisTemplate.opsForHyperLogLog().size(keyList.toArray(new String[0]));
    }

    // 将指定用户id计入DAU
    public void recordDAU(int userId) {
        String dauKey = RedisKeyUtil.getDAUKey(df.format(new Date()));
        redisTemplate.opsForValue().setBit(dauKey, userId, true);
    }

    // 计算连续多天的DAU总数
    public long calculateDAU(Date start, Date end) {
        if (start == null || end == null) {
            throw new IllegalArgumentException("参数不能为空！");
        }

        if (start.after(end)) {
            return 0;
        }

        // 获取该时间范围内每天的dauKey
        List<byte[]> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)) {
            keyList.add(RedisKeyUtil.getDAUKey(df.format(calendar.getTime())).getBytes());
            calendar.add(Calendar.DATE, 1);
        }

        String dauKey = RedisKeyUtil.getDAUKey(df.format(start), df.format(end));
        Long result =  redisTemplate.execute((RedisCallback<Long>) connection -> {
            connection.bitOp(RedisStringCommands.BitOperation.OR, dauKey.getBytes(), keyList.toArray(new byte[0][0]));
            return connection.bitCount(dauKey.getBytes());
        });
        redisTemplate.expire(dauKey, 1, TimeUnit.MINUTES);

        return result != null ? result : 0;
    }

}
